package com.xjggb.characteristic;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class CreateVisibility {
    private static boolean flag = true;
    private static Lock lock = new ReentrantLock();
    public static void main(String[] args) {
        show3();
    }
    public static void show3(){
        Thread t1 = new Thread(() -> {
            while (flag) {
                lock.lock();
                try{
                    //...
                }finally {
                    lock.unlock();
                }
            }
            System.out.println("t1线程结束");

        });
        t1.start();
        flag = false;
        System.out.println("主线程将flag改为false");
    }

    public static void show2(){
        Thread thread = new Thread(() -> {
            while (flag){
                synchronized (CreateVisibility.class){
                    System.out.println("flag = " + flag);
                }

            }
            System.out.println("flag = " + flag);
        });
        thread.start();
        flag=false;
        System.out.println("主线程将flag改为false");
    }


    public static void show1(){
        Thread t1 = new Thread(() -> {
            while (flag) {
                System.out.println("t1线程"+Thread.currentThread().getName());
            }
            System.out.println("t1线程结束");
        });
        t1.start();
        flag = false;
        System.out.println("主线程将flag改为false");
    }

}
